#!/bin/bash
# 验证参数
FILE_COUNT=$#
if((FILE_COUNT <2)); then
    echo ">>> 错误：未传递文件参数！"
    echo "  用法：crontab.sh \"* * * * *\" \"命令或脚本绝对路径\""
    echo "*/1 * * * * root echo 123 >> /root/test.txt"
    echo "  *号：从左到右分别是 分钟（0~59）、小时（0~23）、天（1~31）、月(1~12)、星期(0~6)"
    exit;

fi


# 安装定时器
if [ ! `command -v crontab` ]; then
    # body
    echo "未安装crontabs"
    yum -y install crontabs
fi
# 开启定时服务
if (( 0 == `systemctl status crond | grep 'running' | wc -l` )); then
    echo "启动crond服务"
    systemctl enable crond
    systemctl start crond
fi



CRON=$1
USER=`whoami`
CMD=$2
# 将要运行的命令
echo "$CRON $USER $CMD"

# 当天日期是备份
# cp /etc/crontab /etc/crontab_$(date "+%Y%m%d_%H%m%S")

#配置定时规则
echo "$CRON $USER $CMD" >> /etc/crontab
sudo cat /etc/crontab

# 保存生效
crontab /etc/crontab

#查看任务
crontab -l


#============== 备份一份 =============
# SHELL=/bin/bash
# PATH=/sbin:/bin:/usr/sbin:/usr/bin
# MAILTO=root

# # For details see man 4 crontabs

# # Example of job definition:
# # .---------------- minute (0 - 59)
# # |  .------------- hour (0 - 23)
# # |  |  .---------- day of month (1 - 31)
# # |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# # |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# # |  |  |  |  |
# # *  *  *  *  * user-name  command to be executed
